# -*- coding: UTF-8 -*- #

import tornado
import base64
import os
import pymongo
from tools import Sessions
from tools.models.User import User

_DB = {}

class BaseHandler( tornado.web.RequestHandler ):
    def __init__( self, application, request, status_code = None ):
        tornado.web.RequestHandler.__init__( self, application, request )
        
        if status_code:
            self.set_status( status_code )

        self.application.settings['_db'] = pymongo.collection.Collection(self.db, 'blogis_sessions')

        self.session = self._create_session()

    def get_error_html( self, status_code, **kwargs ):
        if status_code == 404:
            return self.render_string( 'errors/notfound.html' )
        elif status_code == 405:
            return self.render_string( 'errors/methodnotfound.html' )
        elif status_code == 500:
            return self.render_string( 'errors/servererror.html' )

    @property
    def db( self ):
        db = _DB.get( 'db', None )
        if db:
            return db
        else:
            connection = pymongo.Connection( 'localhost', 27017 )
            db = connection.blogis
            _DB['db'] = db
            return db
        
    @property
    def homedir( self ):
        return "%s/" % os.path.curdir

    def get_user_locale(self):
        if not self.user:
            return None
        locale = self.user.locale
        if not locale:
            return tornado.locale.get("ru_RU")
        return tornado.locale.get(locale)

    def Render( self, template, **values ):
        counter = self.get_session( 'counter' )
        if counter:
            counter = str( int( counter ) + 1 )
            self.set_session( 'counter', counter )
        else:
            counter = str( 1 )
            self.set_session( 'counter', counter )
        self.render( template,
                    counter = counter,
                    user = self.user,
                    **values
        )

    def is_avt( self ):
        try:
            user_id = self.session['user_id']
            if user_id:
                return True
            else:
                return False
        except Exception:
            return False
        return True

    @property
    def user( self ):
        try:
            user_id = self.session['user_id']
            if user_id:
                return User(self.db.users.find_one( {'login':user_id} ))
            else:
                return None
        except Exception:
            return None

    def set_session( self, key, value ):
        self.session[key] = value

    def get_session( self, key ):
        try:
            value = self.session[key]
        except Exception:
            value = None
        return value
        return None

    def setcookie( self, name, value, time = None, safe = False ):
        if safe:
            self.set_secure_cookie( name = name, value = base64.b64encode( value ), expires = time )
        else:
            self.set_cookie( name = name, value = base64.b64encode( value ), expires = time )

    def getcookie( self, name, safe = False ):
        if safe:
            cookie = self.get_secure_cookie( name, value = None )
        else:
            cookie = self.get_cookie( name, None )
        if cookie:
            return base64.b64decode( cookie )
        else:
            return None

    def _create_session(self):
        settings = self.application.settings # just a shortcut
        session_id = self.get_secure_cookie(settings.get('session_cookie_name', 'session_id'))
        kw = {'security_model': settings.get('session_security_model', []),
              'duration': settings.get('session_age', 900),
              'ip_address': self.request.remote_ip,
              'user_agent': self.request.headers.get('User-Agent'),
              'regeneration_interval': settings.get('session_regeneration_interval', 240)
              }

        old_session = Sessions.MongoDBSession.load(session_id, settings['_db'])
        if old_session is None or old_session._is_expired(): # create new session
            new_session = Sessions.MongoDBSession(settings['_db'], **kw)

        if old_session is not None:
            if old_session._should_regenerate():
                old_session.refresh(new_session_id=True)
            return old_session
        return new_session

    def finish(self, chunk=None):
        if self.session is not None and self.session._delete_cookie:
            self.clear_cookie(self.settings.get('session_cookie_name', 'session_id'))
        elif self.session is not None:
            self.session.refresh()
            self.set_secure_cookie(self.settings.get('session_cookie_name', 'session_id'),
                                   self.session.session_id,
                                   expires_days=None,
                                   expires=self.session.expires,
                                   path=self.settings.get('session_cookie_path', '/'),
                                   domain=self.settings.get('session_cookie_domain'))
        tornado.web.RequestHandler.finish(self,chunk)